package com.kdg.thread;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

/**a
 * 无锁类使用
 * @author kong
 */
public class AtomicTest {
    public static AtomicInteger atomic = new AtomicInteger(1);

    static AtomicStampedReference<Integer> money = new AtomicStampedReference<>(19,0);

    public static void main(String[] args) {

        //使用atomicInteger
        /*for(int i=0;i<10;i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if(atomic.compareAndSet(1,2)){
                        System.out.println("Thread:"+Thread.currentThread().getName());
                    }else{
                        System.out.println("Thread has update failed!");
                    }
                }
            },"thread"+i).start();
        }*/
        //模拟多个线程同时更新后台数据库为用户充值
        for(int i=0;i<3;i++){
            final int timeStamp = money.getStamp();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true){
                        Integer m = money.getReference();
                        if(m<20){
                            if(money.compareAndSet(m,m+20,timeStamp,timeStamp+1)){
                                System.out.println("余额小于20元，充值成功，余额"+money.getReference()+"元。");
//                                break;
                            }
                        }else{
//                            break;  //余额大于20元
                        }
                    }
                }
            },"Thread"+i).start();
        }

        //模拟多个线程同时更新后台数据库  模拟用户消费
        for(int i=0;i<3;i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final int timeStamp = money.getStamp();
                    while(true){
                        Integer m = money.getReference();
                        if(m>=10){
                            if(money.compareAndSet(m,m-10,timeStamp,timeStamp+1 )){
                                System.out.println("已消费10元，剩余余额"+money.getReference()+"元");
                            }
                        }else{
                            System.out.println("余额不足，请充值");
                        }
                    }
                }
            }, "Thread" + i).start();
        }
    }
}
